/*
*  Copyright 2019-2023 CY
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.ejweixin.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.FileProperties;
import me.zhengjie.modules.ejweixin.domain.NgCaseImg;
import me.zhengjie.modules.ejweixin.service.NgCaseImgService;
import me.zhengjie.modules.ejweixin.domain.vo.NgCaseImgQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;
import org.springframework.web.multipart.MultipartFile;

/**
* @author cy
* @date 2025-04-22
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "案例轮播图管理")
@RequestMapping("/api/ngCaseImg")
public class NgCaseImgController {

    private final NgCaseImgService ngCaseImgService;

    @Value("${file.windows.path}")
    private String uploadDir;

    private final FileProperties properties;
    private final List<String> allowedContentTypes = Arrays.asList("image/jpeg", "image/png", "image/gif");

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('ngCaseImg:list')")
    public void exportNgCaseImg(HttpServletResponse response, NgCaseImgQueryCriteria criteria) throws IOException {
        ngCaseImgService.download(ngCaseImgService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询案例轮播图")
    @ApiOperation("查询案例轮播图")
    @PreAuthorize("@el.check('ngCaseImg:list')")
    public ResponseEntity<PageResult<NgCaseImg>> queryNgCaseImg(NgCaseImgQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(ngCaseImgService.queryAll(criteria,page),HttpStatus.OK);
    }

    @GetMapping("getCaseImgs")
    @Log("查询案例轮播图")
    @ApiOperation("查询案例轮播图")
    @AnonymousAccess
    public ResponseEntity<Object> getCaseImgs(String caseId){
        return new ResponseEntity<>(ngCaseImgService.getCaseImgs(caseId),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增案例轮播图")
    @ApiOperation("新增案例轮播图")
    @PreAuthorize("@el.check('ngCaseImg:add')")
    public ResponseEntity<Object> createNgCaseImg(@Validated @RequestBody NgCaseImg resources){
        ngCaseImgService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改案例轮播图")
    @ApiOperation("修改案例轮播图")
    @PreAuthorize("@el.check('ngCaseImg:edit')")
    public ResponseEntity<Object> updateNgCaseImg(@Validated @RequestBody NgCaseImg resources){
        ngCaseImgService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除案例轮播图")
    @ApiOperation("删除案例轮播图")
    @PreAuthorize("@el.check('ngCaseImg:del')")
    public ResponseEntity<Object> deleteNgCaseImg(@RequestBody List<Integer> ids) {
        ngCaseImgService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/upload")
    @AnonymousAccess
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file, String id) {
        try {
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadPath = Paths.get(uploadDirP);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            if (!allowedContentTypes.contains(file.getContentType())) {
                return ResponseEntity.badRequest().body("只允许上传图片文件");
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());
            ngCaseImgService.saveCaseImg(id, fileName);
            Map res = new HashMap<String, Object>();
            res.put("id", fileName);
            return ResponseEntity.ok(res);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }
}